//
//  ViewController.m
//  QQ聊天列表
//
//  Created by Jorn.Wu on 15/5/23.
//  Copyright (c) 2015年 Jorn.Wu. All rights reserved.
//

#import "ViewController.h"
#import "MessageModel.h"
#import "CellTableView.h"
#import "MessageFrameModel.h"
#import "Constant.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong)NSDictionary *autoReplay;//自动回复消息数组
@property (weak, nonatomic) IBOutlet UITextField *inputTextVeiw;//输入框
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *messages;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.tableView.allowsSelection = NO;//让tableView不可点，即cell不可点
    self.tableView.backgroundColor = kColorWithRGB(200, 200, 200, 1);//可以添加背景图片
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//清除间隔线的颜色
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(keyboardDidChangeFrameNotificationAction:)
                                                name:UIKeyboardWillChangeFrameNotification
                                              object:nil];
    
//    设置左边距
    self.inputTextVeiw.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 0)];
//    让它一直显示
    self.inputTextVeiw.leftViewMode = UITextFieldViewModeAlways;
    
}

- (void)keyboardDidChangeFrameNotificationAction:(NSNotification *)noti{
    self.view.window.backgroundColor = self.tableView.backgroundColor;//改变window的颜色，防止漏缝影响美观；
    CGRect frame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //键盘的实时Y坐标
    CGFloat keyY = frame.origin.y;
    CGFloat keyDuration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];//键盘动画的时间

    [UIView animateWithDuration:keyDuration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, keyY - kScreenSizeHeight);

    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{//当tableView开始滚动时调用
    [self.inputTextVeiw endEditing:YES];//结束编辑
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.inputTextVeiw endEditing:YES];//结束编辑
}

-  (NSMutableArray *)messages{
    if (_messages == nil) {
        NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"messages" ofType:@"plist"]];
        NSMutableArray *messageArr = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            MessageModel *message = [MessageModel messageWithDict:dict];
            
            MessageFrameModel *lastFM = [messageArr lastObject];//取出上一个模型
            
            message.hideTime = [message.time isEqualToString:lastFM.message.time];//对比时间，相同是HideTime为yes；

            MessageFrameModel *frame = [[MessageFrameModel alloc]init];
            frame.message = message;
            [messageArr addObject:frame];
        }
        _messages = messageArr;

    }
    return _messages;
}
#pragma mark -textField代理方法

//添加信息
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    //发消息
    [self addNewMessages:textField.text andType:MessageModelPersonOne];
    
    //自动回复
    NSString *autoStr = [self autoReplayWithText:textField.text];
    [self addNewMessages:autoStr andType:MessageModelPersonTwo];
    
    //4 清空输入框
    self.inputTextVeiw.text = nil;
    //直接return yes 即可
    return YES;
}

- (void)addNewMessages:(NSString *)string andType:(MessageModelType)type{
    //1 添加模型数据
    MessageModel *msg = [[MessageModel alloc]init];
    
    NSDate *date = [[NSDate alloc]init];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    
    NSString *dateWithFormatter = [dateFormatter stringFromDate:date];
    
    msg.time = dateWithFormatter;
    msg.text = string;
    msg.type = type;//谁
    
    //2 设置内容frame
    MessageFrameModel *messageFM = [[MessageFrameModel alloc]init];
    
    messageFM.message = msg;
    [self.messages addObject:messageFM];//添加到cell里面去
    
    //3 刷新表格
    
    [self.tableView reloadData];
    
    // 自动上移，新消息添加在最下面
    NSIndexPath *path = [NSIndexPath indexPathForRow:self.messages.count - 1 inSection:0];//最后一行
    
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    //    atScrollPosition是滚到的位置
    
    
}
//懒加载自动回复消息
- (NSDictionary *)autoReplay{
    if (_autoReplay == nil) {
        _autoReplay = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"autoReplay" ofType:@"plist"]];
    }
    return _autoReplay;
}
- (NSString *)autoReplayWithText:(NSString *)text{
    for (int i = 0; i < text.length; i++ ) {
        NSRange range= {i,1};
        NSString *subStr = [text substringWithRange:range];
        if (self.autoReplay[subStr]) {
            return self.autoReplay[subStr];
        }
    }
    return @"草，会不会聊天，真听不懂你说什么";
}


#pragma mark -隐藏状态栏
- (BOOL)prefersStatusBarHidden{
    return YES;
}

#pragma mark -tableView数据源的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.messages.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageFrameModel *model = self.messages[indexPath.row];
    return model.cellH;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CellTableView *cell = [CellTableView messageCellWithTableView:tableView];
    MessageFrameModel *model = self.messages[indexPath.row];
    cell.messageFrame = model;
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
